import  axios  from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { userStore } from "../../store/user.js";
import { storeToRefs } from 'pinia'
import pina from '../../store/store.js'
export function createRequest (config = {}) {
    const user = userStore(pina)
    const { userData } = storeToRefs(user)
    const router = useRouter()
   const request =  axios.create({
        ...config
    })
   request.interceptors.request.use(config => {
       if (config.url.split('/')[2] === 'login') {
           return config
       }
       const userInfo = userData || JSON.parse(window.localStorage.getItem('userData'))
       if (!userInfo) {
           ElMessage.error('请重新登录')
           router.replace({ path: '/login' })
       }else {
           return config
       }
   })
    request.interceptors.response.use(response => {
        console.log(response)
        switch (response.status) {
            case 200:
                if (response.data.code !== 1 && response.data.type !== "image/png") {
                    ElMessage.error(response.data.msg)
                }
                return response
            break;
            case 401:
                ElMessage.error('请重新登录')
                router.push({path: '/login'}).then(r =>{})
                break;
         }
    }, (error) => {
        if (error.response) {
            if (error.response.status === 500) {
                ElMessage.error('服务器内部错误，请稍后再试！')
                return error
            } else if (error.response.status === 400) {
                ElMessage.error('请求错误，请检查参数是否正确！')
                return error
            }
        }
         else{
            ElMessage.error('网络错误，请检查网络连接！')
        }
    })
   return request
}
